package com.crm.config;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.crm.interceptor.AuthenticationInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @version 1.0
 * @author: CRM_SYSTEM
 * @date: 2022/3/30 23:06
 * @Description:
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private InterceptorConfig interceptorConfig;


    @Override
    public void insertFill(MetaObject metaObject) {
        String userName = getUserName();
        if (metaObject.hasGetter("gmtCreate")) {
            setFieldValByName("gmtCreate", LocalDateTime.now(), metaObject);
        }

        if (metaObject.hasGetter("byCreate")) {
            setFieldValByName("byCreate", userName != null ? userName : "Crm_System", metaObject);
        }

        if (metaObject.hasGetter("gmtModified")) {
            setFieldValByName("gmtModified", LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasGetter("byModified")) {
            setFieldValByName("byModified", userName != null ? userName : "Crm_System", metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userName = getUserName();
        if (metaObject.hasGetter("gmtModified")) {
            setFieldValByName("gmtModified", LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasGetter("byModified")) {
            setFieldValByName("byModified", userName != null ? userName : "Crm_System", metaObject);
        }
    }

    public String getUserName(){

        if (RequestContextHolder.getRequestAttributes()==null){
            return null;
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String token = request.getHeader("token");
        String userName = null;
        if (token != null) {
            userName = JWT.decode(token).getAudience().get(0);
        }
        return userName;
    }
}
